package com.ruoyi.common.utils;

/**
 * @ClassName RollValueUtil
 * @Description TODO
 * @Author zz
 * @Date 2023/12/4
 **/
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.RollValueItem;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
public class RollValueUtil {
    /**
     * @Desc:根据概率计算饰品的roll值区间
     * @author: zz
     * @date: 2023/12/4
     */
    public static Map<String, RollValueItem> calculateItemRanges(Map<String, Double> probabilities) {
        Map<String, RollValueItem> items = new HashMap<>();
        double totalProbability = probabilities.values().stream().mapToDouble(Double::doubleValue).sum();
        int lowerBound = 1;
        int upperBound = 0;
        /**最后一个饰品的索引*/
        int lastIndex = probabilities.size() - 1;
        Iterator<Map.Entry<String, Double>> iterator = probabilities.entrySet().iterator();
        for (int i = 0; iterator.hasNext(); i++) {
            Map.Entry<String, Double> entry = iterator.next();
            String itemName = entry.getKey();
            double probability = entry.getValue();
            if (i == lastIndex) {
                // 最后一个饰品，将剩余的区间分配给它
                upperBound = upperBound <= 1000000 ? 1000000 : upperBound;
            } else {
                // 使用百分比计算upperBound
                upperBound = (int) (lowerBound + ((probability / totalProbability) * 1000000)-1);
            }
            RollValueItem item = new RollValueItem(lowerBound, upperBound);
            items.put(itemName, item);

            lowerBound = upperBound + 1;
        }
        return items;
    }

    /**
     * @Desc: 获取ROLL值所在那个roll区间的饰品ID
     * @author: zz
     * @date: 2023/12/4
     */
    public static String rollItem(int rollValue, Map<String, String> items) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            for (Map.Entry<String, String> entry : items.entrySet()) {
                String json = entry.getValue();
                RollValueItem item = objectMapper.readValue(json, RollValueItem.class);
                if (rollValue >= item.getLower() && rollValue <= item.getUpper()) {
                    return entry.getKey();
                }
            }
        } catch (JsonProcessingException e) {
            log.error("获取ROLL值所在区间饰品ID异常");
            return null;
        }
        return null;
    }
}

